# -*- coding: utf-8 -*-
#coding=utf-8

import web
import os
import config
from action.admin.base import adminAction
from model.image import image
from model.audio import audio
from model.album import album

'''
Admin controller: producing audio administration views.
'''
class refererAction(adminAction):
    def __init__(self, name = '音频管理'):
        adminAction.__init__(self, name)


    def GET(self, name):
        if name == 'list':
            return self.list()
        elif name == 'delete':
            return self.delete()
        elif name == 'add':
            return self.add()
        elif name == 'edit':
            return self.edit()
        else:
            return self.notFound()

    def POST(self, name):
        if name == 'save':
            return self.save()
        elif name == 'deleteBatch':
            return self.deleteBatch()              
        else:
            return self.notFound()

    def list(self):
        inputParams = self.getInput()
        page = int(inputParams['page']) if inputParams.has_key('page') else 1
        count = config.COUNT_PER_PAGE
        offset= (page-1)*count if page > 0 else 0
   
        condition = {}
        audioObj = audio()
        listData = audioObj.getOne('COUNT(*) AS `total`', condition)
        totalCount = listData['total']
        audioList = audioObj.getList('*', condition, 'id desc', str(offset) + ',' + str(count))
        
        pageString = self.getPageStr('/admin/audio/list', page, count, totalCount)
        self.privData['AUDIO_LIST'] = audioList
        self.privData['PAGE_STRING'] = pageString
        self.privData['ALBUM_LIST'] = {}

        condition = {}
        albumList = album().getList('*', condition)
        for item in albumList:
            self.privData['ALBUM_LIST'][item['id']] = item['name']

        return self.display('audioList')

    def add(self):
        condition = {}
        albumList = album().getList('*', condition)
        self.privData['ALBUM_LIST'] = {}
        for item in albumList:
            self.privData['ALBUM_LIST'][item['id']] = item['name']

        self.privData['IMG_ALBUM_LIST'] = {}
        for i in albumList:
            self.privData['IMG_ALBUM_LIST'][i['id']] = {};
            imageList = image().getList('*',{'album': i['id']}, orders="id asc")
            for img in imageList:
                self.privData['IMG_ALBUM_LIST'][i['id']][img['id']] = img['desc']

        self.privData['CURRENT_ALBUM'] = 1
        self.privData['CURRENT_IMG'] = 1
        self.privData['SUBMIT_NAME'] = "thumbnail"

        return self.display('audioAdd')

    def delete(self):
        inputParams = self.getInput()

        condition = {'id': str(inputParams['id'])}
        audioObj = audio().getOne('*', condition)
        if not audioObj:
            return self.error(msg='对象不存在', url=self.makeUrl('/admin/audio/list'))
    
        try:
            audio().delete(condition)

            from uploadmgr import httpFileSystem as fs 
            os.unlink(fs().audioURIFromUUID(audioObj['uuid']))
        except Exception, e:
            return self.error(msg='对象删除失败: %s' % e, url=self.makeUrl('/admin/audio/list'))

        return self.success(msg='对象删除成功', url=self.makeUrl('/admin/audio/list'))

    def deleteBatch(self):
        inputParams = self.getInput()
        try:
            condition = ' id IN (' + inputParams['delitems'] +')'
            audio().delete(condition)
        except Exception, e:
            return self.error(msg='对象删除失败: %s' % e, url=self.makeUrl('/admin/audio/list'))

        return self.success(msg='对象删除成功', url=self.makeUrl('/admin/audio/list'))
 
    def save(self):
        userInput= self.getInput()
        data = {
            'desc':         self.htmlunquote(userInput['desc']),
            'status':       int(userInput['status']),
            'album':        userInput['album'],
            'artist':       userInput['artist'],
            'title':        userInput['title'],
            'thumbnail':    int(userInput['thumbnail']),
        }      

        try:
            condition={'id': int(userInput['id'])}
            audio().update(data, condition)
        except Exception, e:
            return self.error(msg='对象更新失败: %s' % e, url=self.makeUrl('/admin/audio/list'))
        
        return self.success(msg='对象更新成功', url=self.makeUrl('/admin/audio/list'))

    def edit(self):
        inputParams = self.getInput()

        condition={'id': int(inputParams['id'])}
        audioObj = audio().getOne('*', condition)
        if not audioObj:
            return self.error(msg='对象不存在', url=self.makeUrl('/admin/audio/list'))
        self.privData['AUDIO_INFO'] = audioObj 

        condition = {}
        albumList = album().getList('*', condition)
        self.privData['ALBUM_LIST'] = {}
        for item in albumList:
            self.privData['ALBUM_LIST'][item['id']] = item['name']

        self.privData['IMG_ALBUM_LIST'] = {}
        for i in albumList:
            self.privData['IMG_ALBUM_LIST'][i['id']] = {};
            imageList = image().getList('*',{'album': i['id']}, orders="id asc")
            for img in imageList:
                self.privData['IMG_ALBUM_LIST'][i['id']][img['id']] = img['desc']

        self.privData['CURRENT_ALBUM'] = 1
        self.privData['SUBMIT_NAME'] = "thumbnail"
        self.privData['CURRENT_IMG'] = audioObj['thumbnail']

        return self.display('audioEdit')



